//Borrowed Idea from Bruce Allen

//Analog pin 1 for reading in the analog voltage from the MaxSonar device.
//This variable is a constant because the pin will not change throughout execution of this code.
const int anPin = A1;

//Pin number 13 on the arduino board is linked to the onboard LED. For testing purposes,
//this medium will be used to display detonation. For demo purposes, this pin can be
//used to create LED circuit.
const int BoomPin = 3;

//This is the new Power Pin, please insert the '5V' pin into this slot
const int PowerPin = 5;

//This is where the threshold is set. Adjust this value for detonation calibration
const int threshold = 20;

//variables needed to store values
long anVolt, inches, cm;
int sum=0;//Create sum variable so it can be averaged
int avgrange=25;//Quantity of values to average (sample size)

//Broken face makes for no more tests
int fuse = 1;


void setup() {

  //This opens up a serial connection to shoot the results back to the PC console
  Serial.begin(9600);

}

void loop() {

  pinMode(anPin, INPUT);
  pinMode(BoomPin, OUTPUT);
  pinMode(PowerPin, OUTPUT);
  
  digitalWrite(PowerPin, HIGH);
  //Check the Power Status to see if the Sensor should be transmitting
//  if(PowerStatus == 1){
//  	digitalWrite(PowerPin, HIGH); 
//  }
//  else {
//  	digitalWrite(PowerPin, LOW); 
//  }
  
  //MaxSonar Analog reads are known to be very sensitive. See the Arduino forum for more information.
  //A simple fix is to average out a sample of n readings to get a more consistant reading.\\ 
  //Even with averaging I still find it to be less accurate than the pw method.\\ 
  //This loop gets 60 reads and averages them
  for(int i = 0; i < avgrange ; i++)
  {
    //Used to read in the analog voltage output that is being sent by the MaxSonar device.
    //Scale factor for the Sensor is (Vcc/512) per inch. A 5V supply yields ~9.8mV/in
    anVolt = analogRead(anPin);
    sum += anVolt;
    delay(10);
  }  

  inches = sum/avgrange;
  cm = inches * 2.54;
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  
  if(inches < threshold){
	if(fuse == 1){
    		Serial.print("MY HEAD EXPLODE!!!");
    		Serial.println();
                digitalWrite(PowerPin, LOW);
    		for(;;){
	    		digitalWrite(BoomPin, HIGH); 
	    		delay(1000);
	    		digitalWrite(BoomPin,LOW);
	    		delay(1000);
    		}
		fuse = 0;
	}
  }
  
  //reset sample total
  sum = 0;

  delay(100);

} 
